"""
模型管理服务

用于查询和管理可用的AI模型
"""
from typing import List, Optional, Dict, Any
from dataclasses import dataclass
from datetime import datetime, timedelta
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.services.personal_agent_service import PersonalAgentService


@dataclass
class ModelInfo:
    """模型信息"""
    model_id: str
    model_name: str
    usage_count: int = 0
    agents_using: List[str] = None

    def __post_init__(self):
        if self.agents_using is None:
            self.agents_using = []

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "model_id": self.model_id,
            "model_name": self.model_name,
            "usage_count": self.usage_count,
            "agents_using": self.agents_using[:5]  # 只返回前5个
        }


class ModelService:
    """模型服务类"""

    def __init__(self, api_client: Optional[HiAgentAPIClient] = None):
        self.api_client = api_client or HiAgentAPIClient()
        self.agent_service = PersonalAgentService(self.api_client)
        self._cache: Dict[str, Any] = {}
        self._cache_time: Optional[datetime] = None
        self._cache_ttl = timedelta(minutes=30)  # 缓存30分钟

    def get_available_models(
        self,
        use_cache: bool = True,
        workspace_id: Optional[str] = None
    ) -> List[ModelInfo]:
        """
        获取可用的模型列表

        Args:
            use_cache: 是否使用缓存（默认True）
            workspace_id: 工作空间ID（可选）

        Returns:
            模型信息列表
        """
        # 检查缓存
        if use_cache and self._is_cache_valid():
            return self._cache.get("models", [])

        # 从现有智能体中提取模型信息
        models_dict = {}

        try:
            # 获取所有智能体
            apps, _ = self.agent_service.list_personal_agents(workspace_id=workspace_id)

            # 遍历智能体，提取模型信息
            for app in apps:
                try:
                    # 尝试获取草稿配置
                    response = self.api_client.make_request("GetAppSingleModeDraft", {
                        "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID,
                        "AppID": app.app_id
                    })

                    app_config = response.get("AppConfigDraft", {})
                    model_id = app_config.get("ModelID")
                    model_name = app_config.get("ModelName", "")

                    if model_id:
                        if model_id not in models_dict:
                            models_dict[model_id] = ModelInfo(
                                model_id=model_id,
                                model_name=model_name or model_id,
                                usage_count=0,
                                agents_using=[]
                            )

                        models_dict[model_id].usage_count += 1
                        models_dict[model_id].agents_using.append(app.name)

                        # 如果有模型名称，更新它
                        if model_name and not models_dict[model_id].model_name:
                            models_dict[model_id].model_name = model_name

                except Exception:
                    # 如果草稿配置失败，尝试获取已发布配置
                    try:
                        response2 = self.api_client.make_request("GetAppConfig", {
                            "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID,
                            "AppID": app.app_id
                        })

                        app_config_info = response2.get("AppConfigInfo", {})
                        model_id = app_config_info.get("ModelID")
                        model_name = app_config_info.get("ModelName", "")

                        if model_id:
                            if model_id not in models_dict:
                                models_dict[model_id] = ModelInfo(
                                    model_id=model_id,
                                    model_name=model_name or model_id,
                                    usage_count=0,
                                    agents_using=[]
                                )

                            models_dict[model_id].usage_count += 1
                            models_dict[model_id].agents_using.append(app.name)

                            if model_name and not models_dict[model_id].model_name:
                                models_dict[model_id].model_name = model_name

                    except Exception:
                        continue

        except Exception as e:
            raise Exception(f"获取模型列表失败: {str(e)}")

        # 转换为列表并按使用次数排序
        models_list = sorted(
            models_dict.values(),
            key=lambda x: x.usage_count,
            reverse=True
        )

        # 更新缓存
        self._cache["models"] = models_list
        self._cache_time = datetime.now()

        return models_list

    def get_model_by_id(
        self,
        model_id: str,
        use_cache: bool = True,
        workspace_id: Optional[str] = None
    ) -> Optional[ModelInfo]:
        """
        根据ID获取模型信息

        Args:
            model_id: 模型ID
            use_cache: 是否使用缓存
            workspace_id: 工作空间ID

        Returns:
            模型信息，如果不存在返回None
        """
        models = self.get_available_models(use_cache=use_cache, workspace_id=workspace_id)

        for model in models:
            if model.model_id == model_id:
                return model

        return None

    def search_models(
        self,
        keyword: str,
        use_cache: bool = True,
        workspace_id: Optional[str] = None
    ) -> List[ModelInfo]:
        """
        搜索模型

        Args:
            keyword: 搜索关键词（匹配模型ID或名称）
            use_cache: 是否使用缓存
            workspace_id: 工作空间ID

        Returns:
            匹配的模型列表
        """
        models = self.get_available_models(use_cache=use_cache, workspace_id=workspace_id)

        keyword_lower = keyword.lower()
        return [
            model for model in models
            if keyword_lower in model.model_id.lower()
            or keyword_lower in model.model_name.lower()
        ]

    def get_model_statistics(
        self,
        use_cache: bool = True,
        workspace_id: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        获取模型统计信息

        Args:
            use_cache: 是否使用缓存
            workspace_id: 工作空间ID

        Returns:
            统计信息字典
        """
        models = self.get_available_models(use_cache=use_cache, workspace_id=workspace_id)

        total_models = len(models)
        total_usage = sum(model.usage_count for model in models)

        # 最常用的模型
        most_used = models[0] if models else None

        return {
            "total_models": total_models,
            "total_usage": total_usage,
            "most_used_model": most_used.to_dict() if most_used else None,
            "models": [model.to_dict() for model in models]
        }

    def clear_cache(self):
        """清除缓存"""
        self._cache.clear()
        self._cache_time = None

    def _is_cache_valid(self) -> bool:
        """检查缓存是否有效"""
        if not self._cache_time:
            return False

        return datetime.now() - self._cache_time < self._cache_ttl

    def try_common_choices_api(self, workspace_id: Optional[str] = None) -> Dict[str, Any]:
        """
        尝试调用 CommonChoices API 获取模型列表

        注意：此API可能不返回模型列表，仅用于探索性调用

        Args:
            workspace_id: 工作空间ID

        Returns:
            API响应数据
        """
        try:
            response = self.api_client.make_request("CommonChoices", {
                "WorkspaceID": workspace_id or self.api_client.config.DEFAULT_WORKSPACE_ID
            })
            return response
        except Exception as e:
            raise Exception(f"CommonChoices API 调用失败: {str(e)}")
